import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Select,
	Popconfirm as Reconfirm,
	InputNumber,
} from 'antd'
import React, {
	useState,
	useEffect,
	memo,
	useRef,
	useImperativeHandle,
} from 'react'
import {connect} from 'umi'
import type {
	ActionType,
	EditableFormInstance,
	ProColumns,
} from '@ant-design/pro-components'
import {EditableProTable} from '@ant-design/pro-components'
import styles from './index.less'
import {SendTimeOptions, isRecover, isExaminationInterval} from '../constant'
import {integerPattern, twoDecimalPattern} from '@/utils/common/validator'

type DataSourceType = {
	title: any
	itemName: string
	id: React.Key
	labels?: {
		key: string
		label: string
	}[]
	state?: string
	children?: DataSourceType[]
}
const view = memo(
	(props: {
		routerQuery: any
		detail: any
		cRef: any
		driverRewardRules: any
	}) => {
		const {routerQuery, detail, cRef, driverRewardRules} = props
		const [form] = Form.useForm()
		const [releaseTime, setReleaseTime] = useState(1)
		// 可编辑表格
		const actionRef = useRef<ActionType>()
		const editorFormRef = useRef<EditableFormInstance<DataSourceType>>()
		const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
		const [costitemList, setCostitemList] = useState<any[]>([])
		// 可编辑表格
		const proColumns: ProColumns<DataSourceType>[] = [
			{
				title: (
					<>
						<span className="required">* </span> 免租期数
					</>
				),
				dataIndex: 'leaseTerm',
				align: 'center',
				width: 200,
				renderFormItem: () => (
					<InputNumber
						min={1}
						max={driverRewardRules.MAXTERM}
						style={{width: '100%'}}
					/>
				),
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: integerPattern,
							message: '输入的租期不正确',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span>
						<span>免租金额（元）</span>
					</>
				),
				dataIndex: 'amount',
				align: 'center',
				width: 200,
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: twoDecimalPattern,
							message: '输入的发放金额不正确',
						},
						{
							max: 10,
							message: '最长10位',
						},
					],
				},
			},
			{
				title: '操作',
				valueType: 'option',
				align: 'center',
				width: 200,
				fixed: 'right',
				hideInTable:
					routerQuery.pageType === 'detail' &&
					routerQuery.pageType === 'process',
				render: (text, record: any, _, action) => [
					<Button
						type="link"
						key="editable"
						size="small"
						onClick={() => {
							action?.startEditable?.(record.id)
						}}>
						编辑
					</Button>,
					<Reconfirm
						placement="topLeft"
						title="你确定要删除这条数据吗？"
						onConfirm={() => {
							const l = [...costitemList].filter(
								(item: any) => item.id !== record.id,
							)
							setCostitemList(l)
						}}
						okText="确定"
						cancelText="取消">
						<Button type="link" key="delete">
							删除
						</Button>
					</Reconfirm>,
				],
			},
		]

		const onReleaseTimeChange = (value: any) => {
			setReleaseTime(value)
		}

		useEffect(() => {
			if (routerQuery.pageType === 'add') {
				form.setFieldsValue({releaseTime: 1})
			}
		}, [routerQuery])

		// 初始化表单数据
		useEffect(() => {
			if (
				routerQuery.pageType === 'edit' ||
				routerQuery.pageType === 'detail' ||
				routerQuery.pageType === 'process'
			) {
				const obj = detail?.filter(
					(item: any) => item.activitiesType === 3,
				)[0]
				setReleaseTime(() => obj?.releaseTime)
				if (obj?.releaseTime === 3) {
					setCostitemList(() => obj?.detailsDTOList)
				}
				form.setFieldsValue({
					...obj,
					examinationInterval:
						obj?.detailsDTOList[0]?.examinationInterval,
					amount: obj?.detailsDTOList[0]?.amount,
					entityType: obj?.detailsDTOList[0]?.entityType.toString(),
					issueKind: obj?.detailsDTOList[0]?.issueKind.toString(),
				})
			}
		}, [detail])

		useImperativeHandle(cRef, () => ({
			// changeVal 就是暴露给父组件的方法
			getFormData: async () => {
				const value = await form.validateFields()
				return value
			},
			getList: () => costitemList,
			clearCostitemList: () => setCostitemList(()=>[]),

		}))
		return (
			<div className={styles.admittanceAdd}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					<Form
						form={form}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						initialValues={{remember: true}}
						autoComplete="off"
						disabled={
							routerQuery.pageType === 'detail' ||
							routerQuery.pageType === 'process'
						}>
						{releaseTime === 1 || releaseTime === 4 ? (
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="发放时间"
										name="releaseTime"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											onChange={onReleaseTimeChange}
											options={[...SendTimeOptions]}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="免租金额（元）"
										name="amount"
										rules={[
											{required: true, message: '请输入'},
										]}>
										<Input
											placeholder="请输入金额（元）"
											maxLength={10}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="违反规定是否追回"
										name="isRecover"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											options={[...isRecover]}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="考核区间选择"
										name="examinationInterval"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											options={[...isExaminationInterval]}
										/>
									</Form.Item>
								</Col>
							</Row>
						) : null}
						{releaseTime === 2 ? (
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="发放时间"
										name="releaseTime"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											onChange={onReleaseTimeChange}
											options={[...SendTimeOptions]}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="每期免租金额"
										name="amount"
										rules={[
											{required: true, message: '请输入'},
										]}>
										<Input
											placeholder="请输入金额（元）"
											maxLength={10}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="违反规定是否追回"
										name="isRecover"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											options={[...isRecover]}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="考核区间选择"
										name="examinationInterval"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											options={[...isExaminationInterval]}
										/>
									</Form.Item>
								</Col>
							</Row>
						) : null}
						{releaseTime === 3 ? (
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="发放时间"
										name="releaseTime"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											onChange={onReleaseTimeChange}
											options={[...SendTimeOptions]}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="违反规定是否追回"
										name="isRecover"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											options={[...isRecover]}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="考核区间选择"
										name="examinationInterval"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Select
											placeholder="请选择"
											allowClear
											options={[...isExaminationInterval]}
										/>
									</Form.Item>
								</Col>
								<Col span={24} />
								{releaseTime === 3 ? (
									<Col span={24}>
										<div className="tableName">
											{routerQuery.pageType !==
												'detail' &&
											routerQuery.pageType !==
												'process' ? (
												<Button
													type="primary"
													ghost
													size="small"
													style={{
														marginBottom: '12px',
													}}
													onClick={() => {
														actionRef.current?.addEditRecord?.(
															{
																id: `ID${(
																	Math.random() *
																	100000000
																).toFixed(0)}`,
															},
														)
													}}>
													新增
												</Button>
											) : null}
											<EditableProTable<DataSourceType>
												bordered
												rowKey="id"
												key="id"
												actionRef={actionRef}
												editableFormRef={editorFormRef}
												maxLength={5}
												scroll={{
													x: 'max-content',
													y: 480,
												}}
												// 关闭默认的新建按钮
												recordCreatorProps={false}
												columns={proColumns}
												value={costitemList}
												onChange={(value: any) => {
													setCostitemList(value)
												}}
												editable={{
													editableKeys,
													onSave: async () => true,
													onChange:
														setEditableRowKeys,
													actionRender: (
														rows: any,
														config: any,
														dom: any,
													) => [dom.save, dom.cancel],
												}}
											/>
										</div>
									</Col>
								) : null}
							</Row>
						) : null}
					</Form>
				</div>
			</div>
		)
	},
)
export default connect(({user, driverRewardRules}: any) => ({
	user,
	driverRewardRules,
}))(view)
